trait State {
    fn handle(&self, context: &mut Context);
}

// 具体状态 ConcreteStateA
struct ConcreteStateA;

impl State for ConcreteStateA {
    fn handle(&self, context: &mut Context) {
        println!("ConcreteStateA handling request.");
        // 切换到 ConcreteStateB
        context.change_state(Box::new(ConcreteStateB));
    }
}

// 具体状态 ConcreteStateB
struct ConcreteStateB;

impl State for ConcreteStateB {
    fn handle(&self, context: &mut Context) {
        println!("ConcreteStateB handling request.");
        // 切换到 ConcreteStateA
        context.change_state(Box::new(ConcreteStateA));
    }
}

// 状态模式的上下文 Context
struct Context {
    state: Option<Box<dyn State>>,
}

impl Context {
    // 创建 Context 并设置初始状态
    fn new(state: Box<dyn State>) -> Self {
        Self { state: Some(state) }
    }

    // 处理请求并根据当前状态进行处理
    fn request(&mut self) {
        // 临时取出状态以避免后续的不可变借用
        if let Some(state) = self.state.take() {
            state.handle(self);
            // 重新将状态放回，可能已经发生了变化
            self.state = Some(state);
        }
    }

    // 切换状态
    fn change_state(&mut self, state: Box<dyn State>) {
        self.state = Some(state);
    }
}

pub fn main() {
    // 创建 Context 并设置初始状态为 ConcreteStateA
    let mut context = Context::new(Box::new(ConcreteStateA));

    // 处理请求，触发状态切换
    context.request(); // ConcreteStateA 处理请求，切换到 ConcreteStateB
    context.request(); // ConcreteStateB 处理请求，切换到 ConcreteStateA
}
